# -*- coding: utf-8 -*-
# @Project       : sms-text-message-report
# @File Name     : send_email.py
# @Author        : liushuangdan 
# @Date          : 2021/5/7 11:30
# @IDE           : PyCharm
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.header import Header
import smtplib


def send_email(title, content, cc=None, receiver=None):
    sender = 'liushuangdan@csm.com.cn'
    if receiver is None:
        receiver = ['liushuangdan@csm.com.cn']
    if cc is None:
        cc = ['liushuangdan@csm.com.cn']
    # 创建邮件
    msg = MIMEMultipart()
    msg['Subject'] = Header(title, 'utf-8')  # 邮件主题
    msg.attach(MIMEText(content))  # 邮件内容
    msg['from'] = sender  # 发件人
    msg['To'] = ';'.join(receiver)  # 收件人
    msg['Cc'] = ';'.join(cc)  # 抄送
    # 发送邮件
    host = 'mail.csm.com.cn'
    smtp = smtplib.SMTP(host)
    # smtp.login(user="csm\liushuangdan", password="LSD@12345")
    smtp.sendmail(sender, receiver + cc, msg.as_string())
    print('发送邮件完成')


def send_email_with_file(dirpath, filenames, title, content, cc=None, receiver=None):
    sender = 'liushuangdan@csm.com.cn'
    if receiver is None:
        receiver = ['liushuangdan@csm.com.cn']
    if cc is None:
        cc = ['liushuangdan@csm.com.cn']
    print('发送邮件ing')

    # 创建邮件
    msg = MIMEMultipart()
    msg['Subject'] = Header(title, 'utf-8')  # 邮件主题
    msg.attach(MIMEText(content))  # 邮件内容
    msg['from'] = sender  # 发件人
    msg['To'] = ';'.join(receiver)  # 收件人
    msg['Cc'] = ';'.join(cc)  # 抄送

    # 添加附件
    if isinstance(filenames, str):
        filenames = [filenames]
    for filename in filenames:
        part = MIMEApplication(open('{}/{}'.format(dirpath, filename), 'rb').read())
        part.add_header('Content-Disposition', 'attachment', filename=filename)
        msg.attach(part)

    # 发送邮件
    host = 'mail.csm.com.cn'
    smtp = smtplib.SMTP(host)
    smtp.sendmail(sender, receiver + cc, msg.as_string())
    print('完成')


if __name__ == '__main__':
    send_email(title="测试手机报邮件", content="手机报内容", receiver=["zhangquan@csm.com.cn"])